new Vue({
    el: '#app',
    data() {
        return {
            id: '',
            isActive: '',
            tableData: [],// 商品信息
            swiperPic: [],// 轮播图片
            detailPic: [],// 明细图片
            addressData: null,// 默认地址
            loading: false,// 节流阀门
            drawer: false,// 弹窗
            isSelect: '',//选择规格
            Quantity: 1,//数量
        }
    },
    beforeCreate() {
        function setRem() {
            const designWidth = 750; // 设计稿宽度（rpx）
            const maxWidth = 540; // 可选：限制最大宽度（如手机端常见值）
            const screenWidth = Math.min(window.innerWidth, maxWidth);
            const scale = screenWidth / designWidth;
            document.documentElement.style.fontSize = scale + 'px';
        }
        setRem();
    },
    mounted() {
        let URL = window.location.href;
        this.id = getQueryObject(URL, 'id');
        this.init();
    },
    computed: {
        formData() {
            const { tableData, isSelect } = this;
            let obj = tableData.filter(i => i.Specifications_SerialNumber == isSelect)[0];
            return obj || {};
        }
    },
    methods: {
        async init(callback) {
            await Promise.allSettled([
                this.getList(),
                this.getData(),
                this.getAddress(),
            ]);
            callback ? callback() : null;
        },
        async getList() { // 商品信息
            try {
                const data = await generalApi.generalQueryBySQLSerialNumberWithClient({
                    SQLSerialNumber: 'm_daily_execute_unitprice_detail',
                    Condition: utf8ToBase64(`${this.id},%%`),
                })
                if (data.length > 0) {
                    this.isSelect = data[0].Specifications_SerialNumber;
                    this.tableData = data;
                }
            } catch (error) {
                console.error(error);
            }
        },
        async getData() { // 图片
            try {
                const data = await generalApi.generalQueryBySQLSerialNumberWithClient({
                    SQLSerialNumber: 'm_article_picture',
                    Condition: utf8ToBase64(this.id),
                })
                this.swiperPic = data.filter(i => i.Picture_Type == '0')
                this.detailPic = data.filter(i => i.Picture_Type == '1')
            } catch (error) {
                console.error(error);
            }
        },
        async getAddress() { // 查询默认地址
            try {
                const data = await generalApi.generalQueryBySQLSerialNumberWithClient({
                    SQLSerialNumber: 'm_member_address_info',
                    Condition: utf8ToBase64(localStorage.getItem('openId')),
                    ExtensionCondition: utf8ToBase64("AND member_address_info.isDefault='1'"),
                })
                if (data.length > 0) {
                    this.addressData = data[0];
                }
            } catch (error) {
                console.error(error);
            }
        },
        changeCount(elma) {
            if (elma == 'add') { // 增加
                this.Quantity++;
            } else if (elma == 'sub') { // 减少
                if (this.Quantity > 1) {
                    this.Quantity--;
                } else {
                    this.$showToast({
                        title: '不能再减少了'
                    });
                }
            }
        },
        toAddress() {//跳转地址页
            window.location.href = `../../pages/my/my-address.html?type=1`;
        },
        goHome() {// 跳转到首页
            window.location.href = `../../pages/index/index.html`;
        },
        submitOrder() {// 提交订单
            if (isMiniprogram()) { // 小程序环境
                wx.miniProgram.navigateTo({
                    url: `/pages/index/submitOrder?type=0&id=${this.formData.Execute_Unit_Price_SerialNumber}&Quantity=${this.Quantity}`,
                })
            } else { // 其它环境
                this.$showToast({
                    title: '暂未开放'
                });
            }
        },
        async submitCart() {// 加入购物车
            try {
                const data = await generalApi.generalQueryBySQLSerialNumberWithClient({
                    SQLSerialNumber: 'm_member_shopping_trolley_check',
                    Condition: utf8ToBase64(`${getCookie('openId')},${this.formData.Sales_Unit_Price_Detail_SerialNumber}`),
                })
                let lJSONObject_DataSet = {
                    Add: {}, Modify: {}
                }
                if (data.length > 0) {
                    const obj = configOriginal(data[0]);
                    obj.Quantity = accAdd(obj.Quantity , this.Quantity);
                    lJSONObject_DataSet.Modify = { member_shopping_trolley:[obj] }
                } else {
                    const obj = {
                        Open_ID:getCookie('openId'),
                        Sales_Unit_Price_Detail_SerialNumber:this.formData.Sales_Unit_Price_Detail_SerialNumber,
                        Quantity:this.Quantity,
                    }
                    lJSONObject_DataSet.Add = { member_shopping_trolley:[obj] }
                }
                const res = await generalApi.generalSaveByRequestBodyWithClient({
                    Data: lJSONObject_DataSet
                })
                if(res.Status == 'success') {
                    this.$showToast({
                        title:'已成功加入购物车'
                    });
                } else {
                    this.$showToast({
                        title:'购物车添加失败，请重试！'
                    });
                }
            } catch (error) {
                console.error(error);
            }
        }
    },
})
